package me.ingxin.android.permission2.ext

import android.os.Bundle
import android.util.Log
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContract
import androidx.fragment.app.Fragment

/**
 * Created on 2023/7/12 by yin
 * 特殊权限申请
 */
class RequestSpecialFragment<I, O> : Fragment() {

    @Suppress("PrivatePropertyName")
    private val TAG = "RequestSpecialFragment"

    private lateinit var callback: ActivityResultCallback<O>
    private lateinit var contract: ActivityResultContract<I, O>
    private var input: I? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (this::contract.isInitialized && this::callback.isInitialized) {
            registerForActivityResult(contract) {
                removeSelf()
                callback.onActivityResult(it)
            }.launch(input)
        } else {
            removeSelf()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d(TAG, "RequestSpecialFragment onDestroyView @${hashCode()}")
    }

    fun attach(
        input: I?,
        contract: ActivityResultContract<I, O>,
        callback: ActivityResultCallback<O>
    ) {
        this.input = input
        this.contract = contract
        this.callback = callback
    }

    private fun removeSelf() {
        parentFragmentManager.beginTransaction().remove(this).commitAllowingStateLoss()
    }

}